using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using mvcincode.Auth.Requirement;

namespace mvcincode.Auth.Handler
{
    public class MinimumAgeHandler : AuthorizationHandler<MinimumAgeRequirement>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context
            , MinimumAgeRequirement requirement)
        {
            // context.User
            // context.Requirements
            // context.Resource
            // context.Requirements
            
            // requirement只是形式参数, 最终检查的还是Claims
            Claim dateOfBirthClaim = context.User.FindFirst(claim =>
                claim.Type == ClaimTypes.DateOfBirth && claim.Issuer == "http://contoso.com");

            if (dateOfBirthClaim is null)
            {
                return Task.CompletedTask;
            }
            
            var dateOfBirth = Convert.ToDateTime(dateOfBirthClaim.Value);
            int calculatedAge = DateTime.Today.Year - dateOfBirth.Year;
            if (dateOfBirth > DateTime.Today.AddYears(-calculatedAge))
            {
                calculatedAge--;
            }

            if (calculatedAge >= requirement.MinimumAge)
            {
                context.Succeed(requirement);
            }

            return Task.CompletedTask;
        }
    }
}